/**
 * ====================================
 *                ReadMe
 * 1. axios的配置文件
 * 2. 需要导出axios至main.js注册
 * ====================================
 */

//导入axios
import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router/index.js'

const service = axios.create({
  baseURL: 'http://127.0.0.1:7000/',
  timeout: 10000
})

// axios设置请求拦截器,设置响应头token
service.interceptors.request.use(
  config => {
    config.headers['tokenRB'] = localStorage.getItem('tokenRB')
    return config
  },
  err => {
    console.log(err)
  }
)

//响应拦截器
service.interceptors.response.use(
  success => {
    if (success.status == 200) {
      if (success.data.code == 200) {
        return success.data
      } else {
        Message({
          showClose: true,
          message: success.data.msg
        })
      }
    }
    return success.data
  },
  error => {
    if (error.response.status == 500) {
      Message.error('服务器错误！！！')
      router.replace({ path: '/500' })
    } else if (error.response.status == 404) {
      Message.error('页面崩溃了！！！')
      router.replace({ path: '/404' })
    } else if (error.response.status == 503) {
      Message.error('服务超时请重试！！！')
    } else {
      Message.error('页面崩溃了！！！')
      router.replace({ path: '/404' })
    }
    return
  }
)

export default service
